package monitor

import (
	"fmt"
	"image"
	"image/draw"
	"image/png"
	"log"
	"net/http"
	"strings"
	"sync"
	"sync/atomic"

	"github.com/PuerkitoBio/goquery"
)

var (
	graphiteWeight           = 350
	graphiteHeight           = 300
	graphiteHeightAndPadding = 320
)

func graphiteDashboard(httpClient *http.Client, imgHtml string, url string) image.Image {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(imgHtml))
	if err != nil {
		log.Fatal(err)
	}

	var imgs []string
	// Find the review items
	doc.Find("img.graph-img").Each(func(i int, s *goquery.Selection) {
		imgSrc, exists := s.Attr("src")
		if exists {
			imgs = append(imgs, imgSrc)
		}
	})

	var sg sync.WaitGroup
	sg.Add(len(imgs))

	height := len(imgs) * 320
	dashboardImg := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{graphiteWeight, height}})

	var k uint32
	for i := 0; i < len(imgs); i++ {
		i := i
		go func() {
			defer sg.Done()
			img, err := getGrafiteImage(httpClient, url+imgs[i], 1)
			if err == nil {
				kk := atomic.AddUint32(&k, 1) - 1
				r := image.Rectangle{
					Min: image.Point{X: 0, Y: graphiteHeightAndPadding * int(kk)},
					Max: image.Point{X: graphiteWeight, Y: graphiteHeightAndPadding * (int(kk) + 1)},
				}
				draw.Draw(dashboardImg, r, img, image.Point{0, 0}, draw.Src)
			} else {
				fmt.Println(err)
			}
		}()

	}

	sg.Wait()

	return dashboardImg
}

func getGrafiteImage(httpClient *http.Client, url string, hours int) (image.Image, error) {
	//to := int(time.Now().UnixNano() / 1e6)
	//from := to - hours*3600*1000

	resp, err := httpClient.Get(url)
	if err != nil {
		log.Println(url, err)
		return nil, err
	}
	defer resp.Body.Close()

	return png.Decode(resp.Body)

}
